package com.bw.common.photo;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import com.blankj.utilcode.util.LogUtils;
import com.bw.common.R;
import com.bw.common.utils.ToastShowUtils;

import java.io.File;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.shouheng.compress.Compress;
import me.shouheng.compress.strategy.Strategies;
import me.shouheng.compress.strategy.compress.Compressor;

/**
 * 实现思路:
 * 1.权限校验编写:校验权限方法checkPermission():校验需要申请的动态权限是否被用户赋予
 * 2.申请权限:
 * */
public class PhotoActivity extends AppCompatActivity implements View.OnClickListener {

    private String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.CAMERA};
    private final static int PERMISSIONCODE = 100;
    private final static int PHOTOCODE = 101;
    private final static int CAMERACODE = 102;
    private String photoPath;
    private String compressPath;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo);
        findViewById(R.id.photo_btn).setOnClickListener(this);
        findViewById(R.id.camera_btn).setOnClickListener(this);
        findViewById(R.id.canel_btn).setOnClickListener(this);
        if (!checkPermission()){
            //申请权限
            requestPermissions();
        }
    }

    //创建生成的URI
    private Uri createUri(){
        photoPath = getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath()+"/"+System.currentTimeMillis()+".jpg";
        Uri uri = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
            uri = FileProvider.getUriForFile(this,
                    "com.bw.common.my_provider",new File(photoPath));
        }else {
            uri = Uri.fromFile(new File(photoPath));
        }
        return uri;
    }

    private void requestPermissions(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(permissions,PERMISSIONCODE);
        }
    }

    private boolean checkPermission(){
        //权限标志
        boolean perssionFlag = true;
        //校验权限如当前不具有动态权限，修改flag为false
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            for (int i = 0;i < permissions.length;i ++){
                if (checkSelfPermission(permissions[i])
                        != PackageManager.PERMISSION_GRANTED){
                    perssionFlag = false;
                }
            }
        }
        return perssionFlag;
    }

    //图片压缩
    private void compressBitmap(){
        compressPath = getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath()+"/"+System.currentTimeMillis()+".jpg";
        Compressor compress = Compress.Companion.with(this, new File(photoPath))
                .strategy(Strategies.INSTANCE.compressor());
        compress.setMaxHeight(100)
                .setMaxWidth(100)
                .asFlowable()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer(){
                    @Override
                    public void accept(Object o) throws Exception {
                        File file = (File) o;
                        LogUtils.e("压缩完成:"+file.getAbsolutePath());
//                        Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(),null);
//                        LogUtils.e("压缩后图片大小:"+bitmap.getWidth()+"&&"+bitmap.getHeight()
//                                +"&&"+bitmap.getByteCount());
                        Bundle bundle = new Bundle();
                        bundle.putString("photo",file.getAbsolutePath());
                        Intent intent = new Intent();
                        intent.putExtras(bundle);
                        setResult(RESULT_OK,intent);
                        finish();
                    }
                });
    }

    //申请权限返回值获取界面获取是否具有权限
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode,
                permissions, grantResults);
        if (!checkPermission()){
            //由于不具有动态权限关闭当前界面
            ToastShowUtils.showShort("请授予相关权限");
            finish();
        }
    }
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.photo_btn) {
            //intent启动系统图库
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            startActivityForResult(intent,PHOTOCODE);
        } else if (id == R.id.camera_btn) {
            //intent 启动系统相机
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT,createUri());
            startActivityForResult(intent,CAMERACODE);
        } else if (id == R.id.canel_btn) {
            setResult(RESULT_CANCELED);
            finish();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //获取返回值进行处理
        if (resultCode != RESULT_OK){
            return;
        }
        if (requestCode == PHOTOCODE){
            //图库请求状态码
            Uri uri = data.getData();
            //内容提供者，访问对应uri下的图片本地路径
            Cursor cursor = getContentResolver().query(uri,new String[]{MediaStore.Images.Media.DATA},
                    null,null,null);
            while (cursor.moveToNext()){
                photoPath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();//防止内存泄露
        }
        //相机请求状态码->相机已经指定输出图片路径为photoPath->不做获取操作
        if (TextUtils.isEmpty(photoPath)){
            ToastShowUtils.showShort("图片获取失败");
            return;
        }
        //压缩图片处理
        compressBitmap();
    }
}
